---
title: "What Type of Democracy Do Chileans Want?"
author: ""
date: ""
output:
  html_document:
    df_print: paged
    highlight: tango
    theme: united
    toc: yes
    toc_depth: 4
    toc_float: yes
  pdf_document:
    toc: yes
    toc_depth: '3'
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE, results = "hide", fig.width= 9, fig.height=7) 

```

# Clean Data

```{r}
#install.packages("cregg")
#cregg used to evaluate conjoint data
library(cregg)
library(knitr)
```

## Load Data

```{r}
library(readr)
library(tidyverse)
library(dplyr)


#Load in the original conjoint data
conjoint_data <- read_csv("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Original Data/Chile_Conjoint_June.csv")


#Select those who have passed attention check
conjoint_data <- conjoint_data%>% filter(IMC == "Otra")

```

## Recode

```{r}

Chile_conjoint <- conjoint_data%>%
  dplyr::select(caseID = caseID,
                contest_no,
                Profile,
                Female, 
                Age, 
                Income,  
                Education,    
                Chosen_country, 
                "¿Quién puede votar?", 
                "Creación de leyes",
                "Matrimonio igualitario",
                "Presidencia",
                "Reglas para votar",
                "Sistema de partidos",
                "Sistema electoral")%>%
  
  mutate(Sex = 
           case_when(Female == 'Femenino' ~ "Female",
                     Female == 'Masculino' ~ "Male"),
         
         
         Education_eng = 
           case_when(Education == 'Primario incompleto' ~ "Some primary",
                     Education == 'Primario completo' ~ "Primary",
                     Education == 'Secundario incompleto' ~ "Some secondary",
                     Education == 'Secundario completo' ~ "Secondary",
                     Education == 'Terciario incompleto' ~ "Some post-secondary",
                     Education == 'Terciario completo' ~ "Post-secondary",
                     Education == 'Universitario incompleto' ~ "Some university",
                     Education == 'Universitario completo' ~ "University",
                     Education == 'Posgrado completo o incompleto' ~ "Post-graduate"
                    # Education == 'Prefiero no decirlo' ~ "Prefer not to say",

                     
                     
                     ),
         
            Education_cut = 
           case_when(Education == 'Primario incompleto' ~ "Primary",
                     Education == 'Primario completo' ~ "Primary",
                     Education == 'Secundario incompleto' ~ "Secondary",
                     Education == 'Secundario completo' ~ "Secondary",
                     Education == 'Terciario incompleto' ~ "Post-secondary",
                     Education == 'Terciario completo' ~ "Post-secondary",
                     Education == 'Universitario incompleto' ~ "University",
                     Education == 'Universitario completo' ~ "University",
                     Education == 'Posgrado completo o incompleto' ~ "Post-graduate"
                    # Education == 'Prefiero no decirlo' ~ "Prefer not to say",

                     
                     
                     ),
         
             Education_census = 
           case_when(Education == 'Primario incompleto' ~ "Primary",
                     Education == 'Primario completo' ~ "Primary",
                     Education == 'Secundario incompleto' ~ "Secondary",
                     Education == 'Secundario completo' ~ "Secondary",
                     Education == 'Terciario incompleto' ~ "Post-secondary or more",
                     Education == 'Terciario completo' ~ "Post-secondary or more",
                     Education == 'Universitario incompleto' ~ "Post-secondary or more",
                     Education == 'Universitario completo' ~ "Post-secondary or more",
                     Education == 'Posgrado completo o incompleto' ~ "Post-secondary or more"
                    # Education == 'Prefiero no decirlo' ~ "Prefer not to say",

                     
                     
                     ),
         
         
                  
            
         Income_eng = 
           case_when(Income == 'Ningún ingreso' ~ "No income",
                     
                    Income == 'Menos de 125,000 pesos' ~ "Less than 125,000 pesos",
                    
                     Income == 'Entre 125,000 y 190,000 pesos' ~ "Between 125,000 and 190,000 pesos",
                     Income == 'Entre 190,001 y 225,000 pesos' ~ "Between 190,001 and 225,000 pesos",
                     Income == 'Entre 225,001 y 255,000 pesos' ~ "Between 225,001 and 255,000 pesos",
                     Income == 'Entre 255,001 y 300,000 pesos' ~ "Between 255,001 and 300,000 pesos",
                     Income == 'Entre 300,001 y 335,000 pesos' ~ "Between 300,001 and 335,000 pesos",
                     Income == 'Entre 335,001 y 375,000 pesos' ~ "Between 335,001 and 375,000 pesos",
                     Income == 'Entre 375,001 y 420,000 pesos' ~ "Between 375,001 and 420,000 pesos",
                     Income == 'Entre 420,001 y 470,000 pesos' ~ "Between 420,001 and 470,000 pesos",
                    
                     Income == 'Entre 470,001 y 525,000 pesos' ~ "Between 470,001 and 525,000 pesos",

                     Income == 'Entre 525,001 y 600,000 pesos' ~ "Between 525,001 and 600,000 pesos",
                     
                      Income == 'Entre 600,001 y 690,000 pesos' ~ "Between 600,001 y 690,000 pesos pesos",
                     
                      Income == 'Entre 690,001 y 830,000 pesos' ~ "Between 690,001 y 830,000 pesos",
                     
                     Income == 'Entre 830,001 y 1.000,000 pesos"' ~ "Between 830,001 and 1.000,000 pesos",
                     
                     Income == 'Entre 1.000,001 y 1,500,000 pesos' ~ "Between 1.000,001 and 1,500,000 pesos",
                     
                      Income == 'Más de 1,500,000 pesos' ~ "More than 1,500,000 pesos"
                     ),
         
         
           Netquest_ses = 
           case_when(Income == 'Ningún ingreso' ~ "E",
                     
                    Income == 'Menos de 125,000 pesos' ~ "E",
                    
                     Income == 'Entre 125,000 y 190,000 pesos' ~ "E",
                     Income == 'Entre 190,001 y 225,000 pesos' ~ "E",
                     Income == 'Entre 225,001 y 255,000 pesos' ~ "E",
                     Income == 'Entre 255,001 y 300,000 pesos' ~ "E",
                     Income == 'Entre 300,001 y 335,000 pesos' ~ "E",
                     Income == 'Entre 335,001 y 375,000 pesos' ~ "E",
                     Income == 'Entre 375,001 y 420,000 pesos' ~ "E",
                     Income == 'Entre 420,001 y 470,000 pesos' ~ "D",
                    
                     Income == 'Entre 470,001 y 525,000 pesos' ~ "D",

                     Income == 'Entre 525,001 y 600,000 pesos' ~ "D",
                     
                      Income == 'Entre 600,001 y 690,000 pesos' ~ "D",
                     
                      Income == 'Entre 690,001 y 830,000 pesos' ~ "C3",
                     
                     Income == 'Entre 830,001 y 1.000,000 pesos"' ~ "C3",
                     
                     Income == 'Entre 1.000,001 y 1,500,000 pesos' ~ "C2",
                     
                      Income == 'Más de 1,500,000 pesos' ~ "C1b to A"
                     ),
    
           Income_level = 
           case_when(Income == 'Ningún ingreso' ~ "255,000 or less",
                     
                    Income == 'Menos de 125,000 pesos' ~ "255,000 or less",
                    
                     Income == 'Entre 125,000 y 190,000 pesos' ~ "255,000 or less",
                     Income == 'Entre 190,001 y 225,000 pesos' ~ "255,000 or less",
                     Income == 'Entre 225,001 y 255,000 pesos' ~ "255,000 or less",
                     Income == 'Entre 255,001 y 300,000 pesos' ~ "Between 255,001 and 375,000",
                     Income == 'Entre 300,001 y 335,000 pesos' ~ "Between 255,001 and 375,000",
                     Income == 'Entre 335,001 y 375,000 pesos' ~ "Between 255,001 and 375,000",
                     Income == 'Entre 375,001 y 420,000 pesos' ~ "Between 375,001 and 525,000",
                     Income == 'Entre 420,001 y 470,000 pesos' ~ "Between 375,001 and 525,000",
                    
                     Income == 'Entre 470,001 y 525,000 pesos' ~ "Between 375,001 and 525,000",

                     Income == 'Entre 525,001 y 600,000 pesos' ~ "Between 525,001 and 830,000",
                     
                      Income == 'Entre 600,001 y 690,000 pesos' ~ "Between 525,001 and 830,000",
                     
                      Income == 'Entre 690,001 y 830,000 pesos' ~ "Between 525,001 and 830,000",
                     
                     Income == 'Entre 830,001 y 1.000,000 pesos"' ~ "830,001 or more",
                     
                     Income == 'Entre 1.000,001 y 1,500,000 pesos' ~ "830,001 or more",
                     
                      Income == 'Más de 1,500,000 pesos' ~ "830,001 or more"
                     ),
         
         
          Age_cut = cut(Age, breaks = c(-Inf, 36, 56, Inf), labels = c("36 years or less", "37 to 56 years", "Over 56 years")), # By 10
    
           Age_netquest_cut = cut(Age, breaks = c(-Inf, 24, 34, 44, 54, 64, 74, Inf), labels = c("24 years or less", "25 to 34 years", "35 to 44 years","45 to 54 years","55 to 64 years","65 to 74 years","Over 75 years")), # By 10
    
         

    

    
    'Voting Rule' = 
            
            case_when(`Reglas para votar` == 'Votar es un acto voluntario' ~ 'Voluntary voting',
                             
                    `Reglas para votar` == "El voto es obligatorio por ley, pero quienes no votan no reciben ninguna" ~ 'Compulsory voting with no punishment',
                    
                    `Reglas para votar` == 'El voto es obligatorio por ley, y quienes no voten deben pagar una multa de 3 UTM' ~ 'Compulsory voting with a 3 UTM fine'),
          
          'Electoral System' =         
            case_when(`Sistema electoral` == 'A los partidos se les asigna escaños en el Congreso en proporción a la cantidad de votos que obtienen' ~ 'Seats assigned in proportion to votes obtained',
                             
                    `Sistema electoral` == "El partido que obtiene la mayor parte de los votos suele ganar la mayoría de los escaños en el Congreso, incluso si obtiene menos de la mitad de los votos" ~ 'Party with most votes gets majority of seats, even without majority of votes'),
          
          'Party System' =         
            case_when(`Sistema de partidos` == 'Varios partidos compiten en las elecciones y obtienen escaños en el Congreso' ~ 'Multiple parties compete in elections and get seats',
                             
                    `Sistema de partidos` == "En las elecciones, compiten dos partidos principales y obtienen escaños en el Congreso" ~ 'Two parties compete in elections and get seats'),
           'Same-sex Marriage' =         
            case_when(`Matrimonio igualitario` == 'El matrimonio entre personas del mismo sexo es ilegal' ~ 'Same-sex marriage is illegal',
                             
                    `Matrimonio igualitario` == "Los matrimonios de personas del mismo sexo están protegidos por la ley" ~ 'Same-sex marriage is legally protected'),
          
               'Presidency' =         
            case_when(`Presidencia` == 'El presidente tiene el poder de establecer leyes y políticas' ~ 'President has the power to shape laws and policies',
                             
                    `Presidencia` == "El presidente solo tiene un poder simbólico" ~ 'President only has symbolic power'),
          
          
                'Law Creation' =         
            case_when(`Creación de leyes` == 'El presidente puede crear nuevas leyes por decreto, sin votos del Congreso' ~ 'President creates new laws by decree, without congressional approval',
                             
                    `Creación de leyes` == "Las nuevas leyes propuestas deben obtener el apoyo de la mayoría en el Congreso" ~ 'New laws need support of a congressional majority'),
          
          
                  'Who Can Vote' =         
      
            case_when(`¿Quién puede votar?` == 'Todos los adultos tienen el derecho de votar' ~ 'All adults have the right to vote',
                             
                    `¿Quién puede votar?` == "Las personas que continuamente dicen cosas malas sobre Chile no tienen derecho al voto" ~ 'People that say bad things about Chile cannot vote', 
                    
                    
                     `¿Quién puede votar?` == "Las personas que no están informadas sobre política y actualidad no tienen derecho al voto" ~ 'People not informed about politics and current events cannot vote')
                  
          
          
          )
  
```

## Variable Type

```{r}


# Sex
Chile_conjoint$Sex <- as.factor(Chile_conjoint$Sex)


# Education

Chile_conjoint$Education_eng <- factor(Chile_conjoint$Education_eng, levels = c("Some primary","Primary",  "Some secondary", "Secondary","Some post-secondary","Post-secondary", "Some university","University", "Post-graduate"))


Chile_conjoint$Education_cut <- factor(Chile_conjoint$Education_cut, levels = c("Primary", "Secondary", "Post-secondary", "University", "Post-graduate"))



# Age


Chile_conjoint$Age_cut <- factor(Chile_conjoint$Age_cut, levels = c("36 years or less", "37 to 56 years", "Over 56 years"))

# Income
Chile_conjoint$Income_level <- factor(Chile_conjoint$Income_level, levels = c("255,000 or less", "Between 255,001 and 375,000", "Between 375,001 and 525,000", "Between 525,001 and 830,000", "830,001 or more"))


```

```{r}

Chile_conjoint$`Voting Rule` <- factor(Chile_conjoint$`Voting Rule`,
                levels = c("Voluntary voting", "Compulsory voting with no punishment", "Compulsory voting with a 3 UTM fine"))



Chile_conjoint$`Electoral System` <- factor(Chile_conjoint$`Electoral System`,
                levels = c("Party with most votes gets majority of seats, even without majority of votes", "Seats assigned in proportion to votes obtained"))


Chile_conjoint$`Party System` <- factor(Chile_conjoint$`Party System`,
                levels = c("Two parties compete in elections and get seats", "Multiple parties compete in elections and get seats"))



Chile_conjoint$`Same-sex Marriage` <- factor(Chile_conjoint$`Same-sex Marriage`,
                levels = c("Same-sex marriage is illegal", "Same-sex marriage is legally protected"))



Chile_conjoint$`Presidency` <- factor(Chile_conjoint$`Presidency`,
                levels = c("President has the power to shape laws and policies", "President only has symbolic power"))



Chile_conjoint$`Law Creation` <- factor(Chile_conjoint$`Law Creation`,
                levels = c("President creates new laws by decree, without congressional approval", "New laws need support of a congressional majority"))



Chile_conjoint$`Who Can Vote` <- factor(Chile_conjoint$`Who Can Vote`,
                levels = c("All adults have the right to vote", "People that say bad things about Chile cannot vote", "People not informed about politics and current events cannot vote"))

```


## Descriptive statistics

### Demographics

#### Sex

```{r}
Sex_table <-  as.data.frame(prop.table(table(Chile_conjoint$Sex)))

Sex_table <- Sex_table%>% 
  rename(Gender = Var1)%>%
  rename(Sample = Freq)%>%
  mutate(Nat_rep = c(.511, .489))
```

#### Age

```{r}
Age_table <-  as.data.frame(prop.table(table(Chile_conjoint$Age_netquest_cut)))

Age_table <- Age_table%>% 
  rename(Age = Var1)%>%
  rename(Sample = Freq)%>%
  mutate(Nat_rep = c(.1465/.8,
                     .1610/.8, 
                     .1371/.8 , 
                     .1358/.8, 
                     .110/.8, 
                     .0663/.8, 
                     .042/.8))

```

```{r}

library(gridExtra)
Sex_grob <- tableGrob(Sex_table)
Age_grob <- tableGrob(Age_table)



pdf("Demos_Chile_Netquest.pdf")
grid.arrange(Sex_grob, Age_grob, ncol = 1, nrow = 2)
dev.off()
```

#### Education

```{r}

Chile_conjoint$Education_census <- factor(Chile_conjoint$Education_census,
                levels = c("Primary", "Secondary", "Post-secondary or more"))



Education_table <-  as.data.frame(prop.table(table(Chile_conjoint$Education_census)))




Education_table <- Education_table%>% 
  rename(Education = Var1)%>%
  rename(Sample = Freq)%>%
  
  mutate(Nat_rep = c(.256,
                     .446,
                     .298))


```

# Weights

```{r}
library(survey)
```

## Recoding

```{r}
Chile_conjoint_omit <- Chile_conjoint%>%
    mutate(Sex_num = 
           case_when(Sex == 'Female' ~ 1,
                     Sex == 'Male' ~ 0),
           Sex_num = as.numeric(Sex_num),
           
           Education_num = 
           case_when(Education_census == 'Primary' ~ 1,
                     Education_census == 'Secondary' ~ 2,
                     Education_census == 'Post-secondary or more' ~ 3),
           
          Education_num = as.numeric(Education_num), 
          
          Age_num =  
            case_when(Age_netquest_cut == '24 years or less' ~ 1,
                      Age_netquest_cut == '25 to 34 years' ~ 2,
                      Age_netquest_cut == '35 to 44 years' ~ 3,
                      Age_netquest_cut == '45 to 54 years' ~ 4,
                      Age_netquest_cut == '55 to 64 years' ~ 5,
                      Age_netquest_cut == '65 to 74 years' ~ 6,
                      Age_netquest_cut == 'Over 75 years' ~ 7,


            ),
          
          Age_num = as.numeric(Age_num))%>%
  drop_na(Sex_num, Education_num, Age_num)
  
  
  

```

## Raking

```{r}
set.seed(123)
dummy_survey_unweighted <- svydesign(ids = ~caseID, 
                                     data = Chile_conjoint_omit, 
                                     weights = NULL)


Sex_dist <- tibble(Sex_num = c(0, 1), Freq = nrow(Chile_conjoint_omit)*c(0.489, 0.511))

Age_dist <- tibble(Age_num = seq(1, 7, 1), Freq = nrow(Chile_conjoint_omit)*c(0.183125, 0.201250, 0.171375, 0.169750, 0.137500, 0.082875, 0.052500))


Education_dist <- tibble(Education_num = seq(1, 3, 1), Freq = nrow(Chile_conjoint_omit)*c(0.256, 0.446, 0.298))

survey_rake <- rake(design = dummy_survey_unweighted,
                          sample.margins = list(~Sex_num, ~Age_num, ~Education_num),
                          population.margins = list( Sex_dist, Age_dist, Education_dist))




```

## Create tables
```{r}

#rename so the demos are the same
Sex_table <- rename(Sex_table, Subgroup = Gender)

Age_table <- rename(Age_table, Subgroup = Age)

Education_table <- rename(Education_table, Subgroup = Education)

demo_tables <- rbind(Sex_table,
                     Age_table,
                     Education_table)
demo_tables <- tibble(demo_tables)

```

```{r}
library(xtable)
xtable(demo_tables)
```

## Check Balance

```{r}
svymean(Chile_conjoint_omit[, c("Sex_num","Age_num", "Education_num")],
        design = dummy_survey_unweighted,
        na.rm = TRUE)

```

```{r}
svymean(Chile_conjoint_omit[, c("Sex_num","Age_num", "Education_num")],
        design = survey_rake,
        na.rm = TRUE)

```

```{r}
Chile_conjoint_omit$Weight <- 1/survey_rake[["prob"]]

Chile_conjoint_omit <- Chile_conjoint_omit%>%
  dplyr::select(caseID,
                Weight,
                contest_no,
                Profile,
                Chosen_country,
                Sex,
                Education_cut,
                Age_cut,
                Income_level,
                `Voting Rule`,
                `Electoral System`,
                `Party System`,
                `Same-sex Marriage`,
                `Presidency`,
                `Law Creation`,
                `Who Can Vote`)


saveRDS(Chile_conjoint_omit, "~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Analysis Data/Chile_conjoint_June.rds")
```

# Main Model

## Read Analysis Data

```{r}
#Clear and read in analysis data
rm(list=ls())
library(cregg)
library(ggplot2)

set.seed(1234)
#For mac
Chile_conjoint <- readRDS("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Analysis Data/Chile_conjoint_June.rds")

```

## Marginal Mean Main

```{r}
mm_main <- cj(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, id= ~caseID, 
weights = ~Weight, estimate = "mm")
```

```{r, eval = TRUE,echo=FALSE, results = "asis"}
knitr::kable(mm_main)
```





## AMCE Main

```{r}
library(cregg)
set.seed(1234)
amce_main <- cj(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, id= ~caseID, weights = ~Weight, estimate = "amce")


```

```{r, eval = TRUE,echo=FALSE, results = "asis"}
knitr::kable(amce_main)
```






## Create Main Plots

```{r}



p1 <- plot(
  cregg::cj(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, id= ~caseID,weights = ~Weight, estimate = "mm"), vline = 0.5
) + 
     geom_hline(yintercept=c( 4.5, 7.5, 10.5, 13.5, 16.5, 19.5), 
                color = "grey50", size=.2) + 
#geom_point(size = 0.1, stroke = 0, shape = 16) + 
  #ylab(NULL) +
  theme(axis.text.y = element_text(size = 10, vjust = 0.5,face="bold"), 
        axis.text.x = element_text(size = 6, hjust = 0.5, vjust = 1), 
          axis.ticks = element_line(colour = "grey50"), 
          plot.title = element_text(face = "bold"), 
          legend.position = "none", 
           legend.title = element_blank(),
          panel.grid.major.x = element_blank(), 
         panel.grid.minor.x = element_blank(), 
            panel.grid.major.y = element_blank(),
       # panel.grid.minor.y =element_blank(),
        panel.background = element_blank()) + 
  ggplot2::scale_x_continuous(
    limits = c(0.1, 0.85), 
    breaks = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8)
  )+  
  ggplot2::geom_text(
    aes(label = sprintf("%0.3f (%0.3f)", estimate, std.error)),
    colour = "black", 
    size = 4,
    position = position_nudge(y = .5)
  ) 



p2 <- plot(
  cj(Chile_conjoint,
     Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, id= ~caseID,weights = ~Weight, estimate = "amce"), vline = 0
) + 
#geom_point(size = 0.1, stroke = 0, shape = 16) +
  ggplot2::scale_x_continuous(
    limits = c(-0.3, 0.3), 
    breaks = c(-0.3, -0.2, -0.1, 0.0, 0.1, 0.2, 0.3)
  )+  
  ggplot2::geom_text(
    aes(label = ifelse(is.na(std.error), "", sprintf("%0.3f (%0.3f)", estimate, std.error))),
    colour = "black", 
    size = 4,
    position = position_nudge(y = .5)
 ) + 
   geom_hline(yintercept=c( 4.5, 7.5, 10.5, 13.5, 16.5, 19.5), 
                color = "grey50", size=.2) + 
  
  ylab(NULL) +
  theme(axis.text.y = element_blank(), 
        axis.text.x = element_text(size = 6, hjust = 0.5, vjust = 1), 
          axis.ticks = element_line(colour = "grey50"), 
          plot.title = element_text(face = "bold"), 
          legend.position = "none", 
           legend.title = element_blank(),
          panel.grid.major.x = element_blank(), 
         panel.grid.minor.x = element_blank(), 
            panel.grid.major.y = element_blank(),
       # panel.grid.minor.y =element_blank(),
        panel.background = element_blank()) 
  



```

### Figure 1-Main

```{r}

p.main <- gridExtra::grid.arrange(p1, p2, ncol = 2, nrow=1, widths = c(2.8, 1))


ggsave("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/MM_ACME_plot_June.pdf", width = 11, height = 7, units = "in", p.main)
```

# Demographic Differences

## Sex

```{r}

mm_gender <- cj(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, 
alpha = .16, 
id= ~caseID, estimate = "mm", weights = ~ Weight, by = ~Sex)



```

```{r, eval = FALSE,echo=FALSE, results = "asis"}
kable(mm_gender)
```

### Plot sex

```{r}

mm_gender <- na.omit(mm_gender)


plot.gender <- plot(mm_gender, group = "Sex", vline = .5, legend_title = "Sex") + 
     geom_hline(yintercept=c( 4.5, 7.5, 10.5, 13.5, 16.5, 19.5), 
                color = "grey50", size=.2) + 
  
      geom_hline(yintercept=c(1.5, 2.5, 5.5, 8.5, 11.5, 14.5, 17.5, 20.5, 21.5), 
                color = "grey60", size=.2, linetype = "dashed") + 
#geom_point(size = .3, stroke = 0, shape = 16) + 
 # ylab(NULL) +
  theme(#axis.text.y = element_blank(), 
    axis.text.y = element_text(size = 10, vjust = 0.5,face="bold"), 
        axis.text.x = element_text(size = 6, hjust = 0.5, vjust = 1), 
          axis.ticks = element_line(colour = "grey50"), 
          plot.title = element_text(face = "bold"), 
          legend.position = "right", 
          # legend.title = element_blank(),
          panel.grid.major.x = element_blank(), 
         panel.grid.minor.x = element_blank(), 
            panel.grid.major.y = element_blank(),
       # panel.grid.minor.y =element_blank(),
        panel.background = element_blank(),
          strip.text.x = element_text(size = 8)) + 

   
#  ggplot2::geom_text(
#    aes(label = sprintf("%0.3f (%0.3f)", estimate, std.error)),
#    colour = "black", 
  #  size = 3,
#    position = position_nudge(y = .5)
 # )+

  ggplot2::scale_x_continuous(
    limits = c(0.1, 0.85), 
    breaks = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8)
  )

plot.gender
```

```{r, eval = FALSE, include=FALSE}


#ggsave("C:/Users/neils/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/gender_suplot.pdf", width = 8.5, height = 6, units = "in", plot.gender)
```

### F-test sex

```{r, messages = FALSE, results = "asis"}


Chile_conjoint_omit <- na.omit(Chile_conjoint)

cj_anova(Chile_conjoint_omit, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, by = ~Sex)


```

## Education

```{r}
mm_education <- cj(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`,
id= ~caseID, weights = ~ Weight, estimate = "mm",
alpha = .16, 
by = ~ Education_cut)
```

```{r, eval = FALSE,echo=FALSE, results = "asis"}
#kable(mm_education)
```

```{r}

mm_education$BY <- factor(mm_education$BY, levels = c("Primary", "Secondary", "Post-secondary", "University", "Post-graduate"))


plot.education <- plot(mm_education, group = "Education_cut", vline = .5, legend_title = "Education") + 
     geom_hline(yintercept=c( 4.5, 7.5, 10.5, 13.5, 16.5, 19.5), 
                color = "grey50", size=.2) + 
      geom_hline(yintercept=c(1.5, 2.5, 5.5, 8.5, 11.5, 14.5, 17.5, 20.5, 21.5), 
                color = "grey60", size=.2, linetype = "dashed") + 
#geom_point(size = 0.1, stroke = 0, shape = 16) + 
 # ylab(NULL) +
  theme(#axis.text.y = element_blank(), 
    axis.text.y = element_text(size = 10, vjust = 0.5,face="bold"), 
        axis.text.x = element_text(size = 6, hjust = 0.5, vjust = 1), 
          axis.ticks = element_line(colour = "grey50"), 
          plot.title = element_text(face = "bold"), 
          legend.position = "right", 
       #    legend.title = element_blank(),
          panel.grid.major.x = element_blank(), 
         panel.grid.minor.x = element_blank(), 
            panel.grid.major.y = element_blank(),
       # panel.grid.minor.y =element_blank(),
        panel.background = element_blank(),
          strip.text.x = element_text(size = 10)) +  
   
  # ggplot2::geom_text(
  #   aes(label = sprintf("%0.3f (%0.3f)", estimate, std.error)),
  #   colour = "black", 
  #   size = 3,
  #   position = position_nudge(y = .5)
  # ) +
  ggplot2::scale_x_continuous(
    limits = c(0.1, 0.85), 
    breaks = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8)
  )
# +
#   facet_wrap(. ~ BY, drop=TRUE)



plot.education
```

### Plot education

```{r, eval = FALSE, include=FALSE}


#ggsave("C:/Users/neils/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/subplot_education.pdf", width = 10, height = 12, units = "in", plot.education)
```

### F-test education

```{r, messages = FALSE, results = "asis"}

cj_anova(Chile_conjoint_omit, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, by = ~Education_cut)


```

## Age

```{r}

mm_age <- cj(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, 
id= ~caseID, estimate = "mm", 
alpha = .16, weights = ~ Weight,
by = ~Age_cut)

```

### Plot age

```{r}
plot.age <- plot(mm_age, group = "Age_cut", vline = .5, legend_title = "Age") + 
     geom_hline(yintercept=c( 4.5, 7.5, 10.5, 13.5, 16.5, 19.5), 
                color = "grey50", size=.2) + 
      geom_hline(yintercept=c(1.5, 2.5, 5.5, 8.5, 11.5, 14.5, 17.5, 20.5, 21.5), 
                color = "grey60", size=.2, linetype = "dashed") + 
#geom_point(size = 0.1, stroke = 0, shape = 16) + 
 # ylab(NULL) +
  theme(#axis.text.y = element_blank(), 
    axis.text.y = element_text(size = 10, vjust = 0.5,face="bold"), 
        axis.text.x = element_text(size = 6, hjust = 0.5, vjust = 1), 
          axis.ticks = element_line(colour = "grey50"), 
          plot.title = element_text(face = "bold"), 
          legend.position = "right", 
          # legend.title = element_blank(),
          panel.grid.major.x = element_blank(), 
         panel.grid.minor.x = element_blank(), 
            panel.grid.major.y = element_blank(),
       # panel.grid.minor.y =element_blank(),
        panel.background = element_blank(),
          strip.text.x = element_text(size = 10)) +
  
  
  ggplot2::scale_x_continuous(
    limits = c(0.1, 0.85), 
    breaks = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8)
  )
     
#  ggplot2::geom_text(
  #  aes(label = sprintf("%0.3f (%0.3f)", estimate, std.error)),
 #   colour = "black", 
 #   size = 3,
 #   position = position_nudge(y = .5)
  #) +
 # facet_wrap(. ~ BY, drop=TRUE)


plot.age
```

```{r, eval = FALSE, include=FALSE}

#ggsave("C:/Users/neils/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/subplot_age.pdf", width = 10, height = 6, units = "in", plot.age)
```

### F-test age

```{r, messages = FALSE, results = "asis"}

cj_anova(Chile_conjoint_omit, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, by = ~Age_cut)


```

## Income

```{r, message=FALSE}

mm_income <- cj(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`,
id= ~caseID, estimate = "mm", 
alpha = .16, weights = ~ Weight,
by = ~ Income_level)

```

```{r, eval = FALSE,echo=FALSE, results = "asis"}
#kable(mm_income)
```

### Plot income

```{r, message = FALSE}

mm_income$BY <- factor(mm_income$BY, levels = c("255,000 or less", "Between 255,001 and 375,000", "Between 375,001 and 525,000", "Between 525,001 and 830,000", "830,001 or more"))


plot.income <- plot(mm_income, group = "Income_level", vline = .5, legend_title = "Income") + 
     geom_hline(yintercept=c( 4.5, 7.5, 10.5, 13.5, 16.5, 19.5), 
                color = "grey50", size=.2) + 
  
    geom_hline(yintercept=c(1.5, 2.5, 5.5, 8.5, 11.5, 14.5, 17.5, 20.5, 21.5), 
                color = "grey60", size=.2, linetype = "dashed") + 
  
#geom_point(size = 0.1, stroke = 0, shape = 16) + 
 # ylab(NULL) +
  theme(#axis.text.y = element_blank(), 
    axis.text.y = element_text(size = 10, vjust = 0.5,face="bold"), 
        axis.text.x = element_text(size = 6, hjust = 0.5, vjust = 1), 
          axis.ticks = element_line(colour = "grey50"), 
          plot.title = element_text(face = "bold"), 
          legend.position = "right", 
          # legend.title = element_blank(),
          panel.grid.major.x = element_blank(), 
         panel.grid.minor.x = element_blank(), 
            panel.grid.major.y = element_blank(),
       # panel.grid.minor.y =element_blank(),
        panel.background = element_blank(),
       strip.text.x = element_text(size = 6)) + 
  ggplot2::scale_x_continuous(
    limits = c(0.1, 0.85), 
    breaks = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8)
  )
# +  
#   ggplot2::geom_text(
#     aes(label = sprintf("%0.3f (%0.3f)", estimate, std.error)),
#     colour = "black", 
#     size = 3,
#     position = position_nudge(y = .5)
#   ) + 
#   facet_wrap(. ~ BY, drop=TRUE)

plot.income
```

```{r, eval = FALSE, include=FALSE}


#ggsave("C:/Users/neils/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/subplot_income.pdf", width = 10, height = 12, units = "in", plot.income)
```

### F-test income

```{r, messages = FALSE, results = "asis"}

cj_anova(Chile_conjoint_omit, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, by = ~Income_level)


```
## Adjust sizes of subgroup plots



```{r, eval = TRUE}

library(gtable)    
library(grid)
library(gridExtra) 
# Get the widths
g.gender <- ggplotGrob(plot.gender)
g.education <- ggplotGrob(plot.education)
g.age <- ggplotGrob(plot.age)
g.income <- ggplotGrob(plot.income)


# The parts that differs in width
leg.gender <- convertX(sum(with(g.gender$grobs[[15]], grobs[[1]]$widths)), "mm")
leg.education <- convertX(sum(with(g.education$grobs[[15]], grobs[[1]]$widths)), "mm")
leg.age <- convertX(sum(with(g.age$grobs[[15]], grobs[[1]]$widths)), "mm")
leg.income <- convertX(sum(with(g.income$grobs[[15]], grobs[[1]]$widths)), "mm")


g.gender$widths <- g.income$widths
g.education$widths <- g.income$widths
g.age$widths <- g.income$widths


# Add an empty column of "abs(diff(widths)) mm" width on the right of 
# legend box for gA (the smaller legend box)
g.gender$grobs[[15]] <- gtable_add_cols(g.gender$grobs[[15]], unit(abs(diff(c(leg.gender, leg.income))), "mm"))


g.education$grobs[[15]] <- gtable_add_cols(g.education$grobs[[15]], unit(abs(diff(c(leg.education, leg.income))), "mm"))

g.age$grobs[[15]] <- gtable_add_cols(g.age$grobs[[15]], unit(abs(diff(c(leg.age, leg.income))), "mm"))





```


#### Figure 2-Sex

```{r, eval = TRUE}
grid.newpage()
plot.gender.arrange <- grid.arrange(g.gender, nrow = 1)



ggsave("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/gender_subplot_June.pdf", width = 11, height = 8, units = "in", plot.gender.arrange)
```

#### Figure 3-Education

```{r, eval = TRUE}
grid.newpage()
plot.education.arrange <- grid.arrange(g.education, nrow = 1)



ggsave("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/education_subplot_June.pdf", width = 11, height = 8, units = "in", plot.education.arrange)
```
#### Figure 4-Age

```{r, eval = TRUE}
grid.newpage()
plot.age.arrange <- grid.arrange(g.age, nrow = 1)



ggsave("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/age_subplot_June.pdf", width = 11, height = 8, units = "in", plot.age.arrange)
```


#### Figure 5-Income


```{r, eval = TRUE}
grid.newpage()
plot.income.arrange <- grid.arrange(g.income, nrow = 1)



ggsave("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/income_subplot_June.pdf", width = 11, height = 8, units = "in", plot.income.arrange)
```


## Unweighted results

### Main unweighted

```{r}


p.mm.unweight <- plot(
  cregg::cj(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, id= ~caseID, estimate = "mm"), vline = 0.5
) + 
     geom_hline(yintercept=c( 4.5, 7.5, 10.5, 13.5, 16.5, 19.5), 
                color = "grey50", size=.2) + 
#geom_point(size = 0.1, stroke = 0, shape = 16) + 
  #ylab(NULL) +
  theme(axis.text.y = element_text(size = 10, vjust = 0.5,face="bold"), 
        axis.text.x = element_text(size = 6, hjust = 0.5, vjust = 1), 
          axis.ticks = element_line(colour = "grey50"), 
          plot.title = element_text(face = "bold"), 
          legend.position = "none", 
           legend.title = element_blank(),
          panel.grid.major.x = element_blank(), 
         panel.grid.minor.x = element_blank(), 
            panel.grid.major.y = element_blank(),
       # panel.grid.minor.y =element_blank(),
        panel.background = element_blank()) + 
  ggplot2::scale_x_continuous(
    limits = c(0.1, 0.85), 
    breaks = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8)
  ) + 
  ggplot2::geom_text(
    aes(label = sprintf("%0.3f (%0.3f)", estimate, std.error)),
    colour = "black", 
    size = 4,
    position = position_nudge(y = .5)
  ) 



p.amce.unweight <- plot(
  cj(Chile_conjoint,
     Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, id= ~caseID, estimate = "amce"), vline = 0
) + 
#geom_point(size = 0.1, stroke = 0, shape = 16) +
  ggplot2::scale_x_continuous(
    limits = c(-0.3, 0.3), 
    breaks = c(-0.3, -0.2, -0.1, 0.0, 0.1, 0.2, 0.3)
  ) + 
  ggplot2::geom_text(
    aes(label = ifelse(is.na(std.error), "", sprintf("%0.3f (%0.3f)", estimate, std.error))),
    colour = "black", 
    size = 4,
    position = position_nudge(y = .5)
 ) + 
   geom_hline(yintercept=c( 4.5, 7.5, 10.5, 13.5, 16.5, 19.5), 
                color = "grey50", size=.2) + 
  
  ylab(NULL) +
  theme(axis.text.y = element_blank(), 
        axis.text.x = element_text(size = 6, hjust = 0.5, vjust = 1), 
          axis.ticks = element_line(colour = "grey50"), 
          plot.title = element_text(face = "bold"), 
          legend.position = "none", 
           legend.title = element_blank(),
          panel.grid.major.x = element_blank(), 
         panel.grid.minor.x = element_blank(), 
            panel.grid.major.y = element_blank(),
       # panel.grid.minor.y =element_blank(),
        panel.background = element_blank()) 
  




```



#### Figure SM1-Main Unweighted

```{r}

p.main.unweighted <- gridExtra::grid.arrange(p.mm.unweight, p.amce.unweight, ncol = 2, nrow=1, widths = c(2.8, 1))


ggsave("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/MM_ACME_unweighted_June.pdf", width = 11, height = 7, units = "in", p.main.unweighted)
```





### Sex unweighted


```{r}

mm_gender_unweighted <- cj(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, 
alpha = .16, 
id= ~caseID, estimate = "mm", by = ~Sex)



```


```{r}
plot.gender.unweighted <- plot(mm_gender_unweighted, group = "Sex", vline = .5, legend_title = "Sex") + 
     geom_hline(yintercept=c( 4.5, 7.5, 10.5, 13.5, 16.5, 19.5), 
                color = "grey50", size=.2) + 
    
    geom_hline(yintercept=c(1.5, 2.5, 5.5, 8.5, 11.5, 14.5, 17.5, 20.5, 21.5), 
                color = "grey60", size=.2, linetype = "dashed") + 
  
#geom_point(size = .3, stroke = 0, shape = 16) + 
 # ylab(NULL) +
  theme(#axis.text.y = element_blank(), 
    axis.text.y = element_text(size = 10, vjust = 0.5,face="bold"), 
        axis.text.x = element_text(size = 6, hjust = 0.5, vjust = 1), 
          axis.ticks = element_line(colour = "grey50"), 
          plot.title = element_text(face = "bold"), 
          legend.position = "right", 
          # legend.title = element_blank(),
          panel.grid.major.x = element_blank(), 
         panel.grid.minor.x = element_blank(), 
            panel.grid.major.y = element_blank(),
       # panel.grid.minor.y =element_blank(),
        panel.background = element_blank(),
          strip.text.x = element_text(size = 8)) + 

   
  # ggplot2::geom_text(
  #   aes(label = sprintf("%0.3f (%0.3f)", estimate, std.error)),
  #   colour = "black", 
  #   size = 3,
  #   position = position_nudge(y = .5)
  # ) +

  ggplot2::scale_x_continuous(
    limits = c(0.2, 0.85), 
    breaks = c(0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8)) 
  
 
  #  +  
  # facet_wrap(. ~ BY, drop=TRUE)

```


### Education unweighted

```{r}
mm_education_unweighted <- cj(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`,
id= ~caseID, estimate = "mm",
alpha = .16, 
by = ~ Education_cut)
```




```{r}
mm_education_unweighted$BY <- factor(mm_education_unweighted$BY, levels = c("Primary", "Secondary", "Post-secondary", "University", "Post-graduate"))


plot.education.unweighted <- plot(mm_education_unweighted, group = "Education_cut", vline = .5, legend_title = "Education") + 
     geom_hline(yintercept=c( 4.5, 7.5, 10.5, 13.5, 16.5, 19.5), 
                color = "grey50", size=.2) + 
    
    geom_hline(yintercept=c(1.5, 2.5, 5.5, 8.5, 11.5, 14.5, 17.5, 20.5, 21.5), 
                color = "grey60", size=.2, linetype = "dashed") + 
  
#geom_point(size = 0.1, stroke = 0, shape = 16) + 
 # ylab(NULL) +
  theme(#axis.text.y = element_blank(), 
    axis.text.y = element_text(size = 10, vjust = 0.5,face="bold"), 
        axis.text.x = element_text(size = 6, hjust = 0.5, vjust = 1), 
          axis.ticks = element_line(colour = "grey50"), 
          plot.title = element_text(face = "bold"), 
          legend.position = "right", 
       #    legend.title = element_blank(),
          panel.grid.major.x = element_blank(), 
         panel.grid.minor.x = element_blank(), 
            panel.grid.major.y = element_blank(),
       # panel.grid.minor.y =element_blank(),
        panel.background = element_blank(),
          strip.text.x = element_text(size = 8)) +  
   
  #  ggplot2::geom_text(
  #   aes(label = sprintf("%0.3f (%0.3f)", estimate, std.error)),
  #   colour = "black",
  #   size = 2,
  #   position = position_nudge(y = .5)
  # ) +
  ggplot2::scale_x_continuous(
    limits = c(0.2, 0.85), 
    breaks = c(0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8))
  # # +
  # facet_wrap(. ~ BY, drop=TRUE)
```



### Age unweighted

```{r}

mm_age_unweighted <- cj(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, 
id= ~caseID, estimate = "mm", alpha = .16, by = ~Age_cut)

```


```{r}
plot.age.unweighted <- plot(mm_age_unweighted, group = "Age_cut", vline = .5, legend_title = "Age") + 
     geom_hline(yintercept=c( 4.5, 7.5, 10.5, 13.5, 16.5, 19.5), 
                color = "grey50", size=.2) + 
    
    geom_hline(yintercept=c(1.5, 2.5, 5.5, 8.5, 11.5, 14.5, 17.5, 20.5, 21.5), 
                color = "grey60", size=.2, linetype = "dashed") + 
  
#geom_point(size = 0.1, stroke = 0, shape = 16) + 
 # ylab(NULL) +
  theme(#axis.text.y = element_blank(), 
    axis.text.y = element_text(size = 10, vjust = 0.5,face="bold"), 
        axis.text.x = element_text(size = 6, hjust = 0.5, vjust = 1), 
          axis.ticks = element_line(colour = "grey50"), 
          plot.title = element_text(face = "bold"), 
          legend.position = "right", 
          # legend.title = element_blank(),
          panel.grid.major.x = element_blank(), 
         panel.grid.minor.x = element_blank(), 
            panel.grid.major.y = element_blank(),
       # panel.grid.minor.y =element_blank(),
        panel.background = element_blank(),
          strip.text.x = element_text(size = 8)) +
  
  
  ggplot2::scale_x_continuous(
    limits = c(0.2, 0.85), 
    breaks = c(0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8)
  )
# +  
#      
#   ggplot2::geom_text(
#     aes(label = sprintf("%0.3f (%0.3f)", estimate, std.error)),
#     colour = "black", 
#     size = 2,
#     position = position_nudge(y = .5)
#   )
#     +
#   facet_wrap(. ~ BY, drop=TRUE)


```



### Income unweighted

```{r, message=FALSE}

mm_income_unweighted <- cj(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`,
id= ~caseID, estimate = "mm", 
alpha = .16, by = ~ Income_level)

```

```{r, message = FALSE}

mm_income_unweighted$BY <- factor(mm_income_unweighted$BY, levels = c("255,000 or less", "Between 255,001 and 375,000", "Between 375,001 and 525,000", "Between 525,001 and 830,000", "830,001 or more"))


plot.income.unweighted <- plot(mm_income_unweighted, group = "Income_level", vline = .5, legend_title = "Income") + 
     geom_hline(yintercept=c( 4.5, 7.5, 10.5, 13.5, 16.5, 19.5), 
                color = "grey50", size=.2) + 
    
    geom_hline(yintercept=c(1.5, 2.5, 5.5, 8.5, 11.5, 14.5, 17.5, 20.5, 21.5), 
                color = "grey60", size=.2, linetype = "dashed") + 
  
#geom_point(size = 0.1, stroke = 0, shape = 16) + 
 # ylab(NULL) +
  theme(#axis.text.y = element_blank(), 
    axis.text.y = element_text(size = 10, vjust = 0.5,face="bold"), 
        axis.text.x = element_text(size = 6, hjust = 0.5, vjust = 1), 
          axis.ticks = element_line(colour = "grey50"), 
          plot.title = element_text(face = "bold"), 
          legend.position = "right", 
          # legend.title = element_blank(),
          panel.grid.major.x = element_blank(), 
         panel.grid.minor.x = element_blank(), 
            panel.grid.major.y = element_blank(),
       # panel.grid.minor.y =element_blank(),
        panel.background = element_blank(),
       strip.text.x = element_text(size = 6)) + 
  ggplot2::scale_x_continuous(
    limits = c(0.2, 0.85), 
    breaks = c(0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8)
  ) 
# +
#   ggplot2::geom_text(
#     aes(label = sprintf("%0.3f (%0.3f)", estimate, std.error)),
#     colour = "black", 
#     size = 2,
#     position = position_nudge(y = .5)
#   )
# + 
#   facet_wrap(. ~ BY, drop=TRUE)

```



## Adjust sizes of unweighted plots




```{r, eval = TRUE}

library(gtable)    
library(grid)
library(gridExtra) 
# Get the widths
g.gender.unweighted <- ggplotGrob(plot.gender.unweighted)
g.education.unweighted <- ggplotGrob(plot.education.unweighted)
g.age.unweighted <- ggplotGrob(plot.age.unweighted)
g.income.unweighted <- ggplotGrob(plot.income.unweighted)


# The parts that differs in width
leg.gender.unweighted <- convertX(sum(with(g.gender.unweighted$grobs[[15]], grobs[[1]]$widths)), "mm")
leg.education.unweighted <- convertX(sum(with(g.education.unweighted$grobs[[15]], grobs[[1]]$widths)), "mm")
leg.age.unweighted <- convertX(sum(with(g.age.unweighted$grobs[[15]], grobs[[1]]$widths)), "mm")
leg.income.unweighted <- convertX(sum(with(g.income.unweighted$grobs[[15]], grobs[[1]]$widths)), "mm")


g.gender.unweighted$widths <- g.income.unweighted$widths
g.education.unweighted$widths <- g.income.unweighted$widths
g.age.unweighted$widths <- g.income.unweighted$widths


# Add an empty column of "abs(diff(widths)) mm" width on the right of 
# legend box for gA (the smaller legend box)
g.gender.unweighted$grobs[[15]] <- gtable_add_cols(g.gender.unweighted$grobs[[15]], unit(abs(diff(c(leg.gender.unweighted, leg.income.unweighted))), "mm"))


g.education.unweighted$grobs[[15]] <- gtable_add_cols(g.education.unweighted$grobs[[15]], unit(abs(diff(c(leg.education.unweighted, leg.income.unweighted))), "mm"))

g.age.unweighted$grobs[[15]] <- gtable_add_cols(g.age.unweighted$grobs[[15]], unit(abs(diff(c(leg.age.unweighted, leg.income.unweighted))), "mm"))





```


#### Figure SM2-Sex Unweighted

```{r, eval = TRUE}
grid.newpage()
plot.gender.unweighted.arrange <- grid.arrange(g.gender.unweighted, nrow = 1)



ggsave("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/subplot_gender_unweighted_June.pdf", width = 11, height = 8, units = "in", plot.gender.unweighted.arrange)
```

#### Figure SM3-Education Unweighted

```{r, eval = TRUE}
grid.newpage()
plot.education.unweighted.arrange <- grid.arrange(g.education.unweighted, nrow = 1)



ggsave("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/subplot_education_unweighted_June.pdf", width = 11, height = 8, units = "in", plot.education.unweighted.arrange)
```
#### Figure SM4-Age Unweighted

```{r, eval = TRUE}
grid.newpage()
plot.age.unweighted.arrange <- grid.arrange(g.age.unweighted, nrow = 1)



ggsave("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/subplot_age_unweighted_June.pdf", width = 11, height = 8, units = "in", plot.age.unweighted.arrange)
```


#### Figure SM5-Income Unweighted


```{r, eval = TRUE}
grid.newpage()
plot.income.unweighted.arrange <- grid.arrange(g.income.unweighted, nrow = 1)



ggsave("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/subplot_income_unweighted_June.pdf", width = 11, height = 8, units = "in", plot.income.unweighted.arrange)
```


# Diagnostics

## Carryover effects

```{r, messages = FALSE, warning = FALSE}

Chile_conjoint$contest_no <- as.factor(Chile_conjoint$contest_no)
mm_contest <- cj(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, 
id= ~caseID, estimate = "mm",weights = ~ Weight,
alpha = .16,
by = ~contest_no)

```

```{r, eval = FALSE,echo=FALSE, results = "asis"}
#kable(mm_contest)
```

### Plot carryover

```{r}
plot.contest <- plot(mm_contest, group = "contest_no", vline = .5, legend_title = "Task") + 
     geom_hline(yintercept=c( 4.5, 7.5, 10.5, 13.5, 16.5, 19.5), 
                color = "grey50", size=.2) + 
        geom_hline(yintercept=c(1.5, 2.5, 5.5, 8.5, 11.5, 14.5, 17.5, 20.5, 21.5), 
                color = "grey60", size=.2, linetype = "dashed") + 
#geom_point(size = 0.1, stroke = 0, shape = 16) + 
 # ylab(NULL) +
  theme(#axis.text.y = element_blank(), 
    axis.text.y = element_text(size = 10, vjust = 0.5,face="bold"), 
        axis.text.x = element_text(size = 6, hjust = 0.5, vjust = 1), 
          axis.ticks = element_line(colour = "grey50"), 
          plot.title = element_text(face = "bold"), 
          legend.position = "right", 
       #    legend.title = element_blank(),
          panel.grid.major.x = element_blank(), 
         panel.grid.minor.x = element_blank(), 
            panel.grid.major.y = element_blank(),
       # panel.grid.minor.y =element_blank(),
        panel.background = element_blank(),
          strip.text.x = element_text(size = 8)) +  
   
 # ggplot2::geom_text(
  #  aes(label = sprintf("%0.3f (%0.3f)", estimate, std.error)),
 #   colour = "black", 
 #   size = 2,
   # position = position_nudge(y = .5)
  #) +
  ggplot2::scale_x_continuous(
    limits = c(0.2, 0.85), 
    breaks = c(0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8)
  )

plot.contest
```

### Figure SM7-Carryover

```{r}

ggsave("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/carryover_suplot_June.pdf", width = 11, height = 8, units = "in", plot.contest)
```

### F-test carryover

```{r, messages = FALSE, results = "asis"}
cj_anova(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, by = ~contest_no)


```

## Profile order effects

```{r}

Chile_conjoint$Profile <- as.factor(Chile_conjoint$Profile)
mm_profile <- cj(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`,
id= ~caseID, estimate = "mm",weights = ~ Weight,
alpha = .16,
by = ~Profile)

```

```{r, eval = FALSE,echo=FALSE, results = "asis"}
#kable(mm_profile)
```

```{r}

plot.profile <- 

  plot(mm_profile, group  ="Profile", vline = .5) + 

  
  guides(fill = guide_legend(reverse = TRUE)) +

  
     geom_hline(yintercept=c( 4.5, 7.5, 10.5, 13.5, 16.5, 19.5), 
                color = "grey50", size=.2) + 
        geom_hline(yintercept=c(1.5, 2.5, 5.5, 8.5, 11.5, 14.5, 17.5, 20.5, 21.5), 
                color = "grey60", size=.2, linetype = "dashed") + 
#geom_point(size = 0.1, stroke = 0, shape = 16) + 
 # ylab(NULL) +
  theme(#axis.text.y = element_blank(), 
    axis.text.y = element_text(size = 10, vjust = 0.5,face="bold"), 
        axis.text.x = element_text(size = 6, hjust = 0.5, vjust = 1), 
          axis.ticks = element_line(colour = "grey50"), 
          plot.title = element_text(face = "bold"), 
          legend.position = "right", 
       #    legend.title = element_blank(),
          panel.grid.major.x = element_blank(), 
         panel.grid.minor.x = element_blank(), 
            panel.grid.major.y = element_blank(),
       # panel.grid.minor.y =element_blank(),
        panel.background = element_blank(),
          strip.text.x = element_text(size = 8)) +
      scale_fill_discrete(breaks = c("1","2")) +
  ggplot2::scale_x_continuous(
    limits = c(0.2, 0.85), 
    breaks = c(0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8)
  ) 

plot.profile
```


### Figure SM8-Carryover

```{r}

ggsave("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/profile_suplot_June.pdf", width = 11, height = 8, units = "in", plot.profile)
```

### F-test profile

```{r, messages = FALSE, results = "asis"}
cj_anova(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, by = ~Profile)


```

```{r, eval = FALSE}
## ---- echo=FALSE-----------------------------------------------------
#library(knitr)

#purl("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Command Files/Chileans_Want_Supplementary.Rmd")



```

```{r, eval = FALSE, echo = FALSE}
sink("Chileans_Want_Supplementary_June.txt")

source(("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Command Files/Chileans_Want_Supplementary.R"),echo=T, max.deparse.length=1e3, encoding = "UTF-8")
sink()

```
